package com.wennn.top.common.vo;

import lombok.Data;
import lombok.ToString;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.function.Consumer;

@Data
@ToString
public class IResult<T> implements Serializable {
    public static final String OK = "200";
    public static final String FAIL = "500";

    private String code;
    private Object msg;
    private T data;

    public IResult() {
    }

    public IResult(String code, Object msg) {
        this.code = code;
        this.msg = msg;
    }

    public static IResult ok() {
        return new IResult().code(OK);
    }

    public static <T> IResult ok(T data) {
        return IResult.ok().data(data);
    }

    public static IResult fail(String code, String msg) {
        return new IResult(code, msg);
    }

    public static IResult fail(String msg) {
        return new IResult(FAIL, msg);
    }

    public IResult data(T data) {
        this.data = data;
        return this;
    }

    public IResult msg(String msg) {
        this.msg = msg;
        return this;
    }

    public IResult code(String code) {
        this.code = code;
        return this;
    }

    public IResult msg(String code, String msg) {
        this.msg = msg;
        this.code = code;
        return this;
    }

    public IResult addMsg(String msg) {
        if (!(this.msg instanceof ArrayList)) {
            this.msg = new ArrayList();
        }
        ((ArrayList) this.msg).add(msg);
        return this;
    }

    public IResult andOk(Consumer<IResult> consumer) {
        if (isOk()) {
            consumer.accept(this);
        }
        return this;
    }

    public IResult andFail(Consumer<IResult> consumer) {

        if (isOk()) {
            consumer.accept(this);
        }
        return this;
    }

    public boolean isOk() {
        return OK.equals(this.code);
    }
}
